package com.ygq.seckill.controller;

import com.ygq.seckill.entity.User;
import com.ygq.seckill.service.GoodsService;
import com.ygq.seckill.service.UserService;
import com.ygq.seckill.vo.GoodsVo;
import com.ygq.seckill.vo.RespBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    //手动渲染
    @Resource
    private ThymeleafViewResolver thymeleafViewResolver;
    @Resource
    private GoodsService goodsService;
//    @GetMapping("/toList")
////    public String goodsList(Model model,
////                            @CookieValue("userTicket") String ticket,
////                            HttpServletRequest request,
////                            HttpServletResponse response){
//
//    public String goodsList(Model model, User user){
//         //如果 cookie 没有生成
////        if (!StringUtils.hasText(ticket)) {
////            return "login";
////        }
////        //从redis获取user
////        User user = userService.getUserByCookie(ticket, request, response);
//
//        //如果用户没有登录
//        if (user == null) {
//            return "login";
//        }
//        model.addAttribute("user", user);
//        model.addAttribute("goodsList", goodsService.findGoodsVo());
//        return "goodsList";
//    }
    //使用redis缓存整个页面
    @GetMapping(value = "/toList",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model,
                         User user,
                         HttpServletResponse response,
                         HttpServletRequest request){

        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String)valueOperations.get("goodsList");
        if(StringUtils.hasText(html)){
            return html;
        }
        if(user==null){ //用户未登录
            return "login";
        }
        model.addAttribute("user", user);

        model.addAttribute("goodsList",goodsService.findGoodsVo());

        //若从redis中获取的内容为空，则手动渲染然后存入redis
        WebContext webContext = new WebContext(request, response,
                request.getServletContext(),
                request.getLocale(),
                model.asMap());

        html=thymeleafViewResolver.getTemplateEngine().process("goodsList",webContext);

        if(StringUtils.hasText(html)){
            valueOperations.set("goodsList",html,60, TimeUnit.SECONDS);
        }
        return html;
    }

    //跳转商品详情页面
    @RequestMapping(value = "/toDetail/{goodsId}")
    @ResponseBody
    public String toDetail(Model model, User user,
                           @PathVariable Long goodsId,
                           HttpServletResponse response,
                           HttpServletRequest request
    ) {


        //使用页面缓存
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsDetail:" + goodsId);
        if (StringUtils.hasText(html)) {
            return html;
        }

        model.addAttribute("user", user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);

        //*****添加倒计时功能代码段-start******
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date newDate = new Date();

        int secKillStatus=0;//秒杀状态 0未开始 1进行中 2结束
        int remainSeconds=0; //开始倒计时秒数 -1表示结束

        if(newDate.before(startDate)){ //秒杀未开始
            remainSeconds=(int)(startDate.getTime()-newDate.getTime())/1000;
        }else if(newDate.after(endDate)){//秒杀结束
            secKillStatus=2;
            remainSeconds=-1;
        }else {
            secKillStatus=1;
            remainSeconds=0;
        }
        model.addAttribute("secKillStatus",secKillStatus);
        model.addAttribute("remainSeconds",remainSeconds);
        //********添加倒计时功能代码段-end ****
        model.addAttribute("goods", goodsVo);
        //将数据交给 model 给前端页面处理
        //return "goodsDetail";
        //如果为 null，手动渲染，存入 redis 中
        WebContext webContext =
                new WebContext(request, response,
                                request.getServletContext(),
                                request.getLocale(),
                                model.asMap());
        html = thymeleafViewResolver.getTemplateEngine()
                .process("goodsDetail", webContext);

        if (StringUtils.hasText(html)) {
        //设置每 60s 更新一次缓存, 即 60s 后, 该页面缓存失效, Redis 会清除该页面缓存
            valueOperations.set("goodsDetail:" + goodsId, html, 60, TimeUnit.SECONDS);
        }
        return html;
    }
    @RequestMapping("/updpwd")
    @ResponseBody
    public RespBean updatePassword(String userTicket,
                                   String password,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {
        return userService.updatePassword(userTicket, password, request, response);
    }
}
